package com.gimi.cloud.bbp.task.util;

import com.alibaba.fastjson.JSON;
import com.gimi.cloud.bbp.dto.log.LogScheduleJobDTO;
import com.gimi.cloud.bbp.dto.task.ScheduleJobDTO;
import com.gimi.cloud.bbp.task.common.springutil.SpringUtil;
import com.gimi.cloud.bbp.task.service.LogScheduleJobService;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 定时任务
 * @author wbj
 * @date 2018-01-08
 */
public class ScheduleJob extends QuartzJobBean {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private ExecutorService service = Executors.newSingleThreadExecutor(); 
	
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		String jsonJob = context.getMergedJobDataMap().getString(ScheduleUtils.JOB_PARAM_KEY);
		ScheduleJobDTO scheduleJob =JSON.parseObject(jsonJob, ScheduleJobDTO.class);
		//获取spring bean
		LogScheduleJobService scheduleJobLogService = SpringUtil.getBean(LogScheduleJobService.class);
        //数据库保存执行记录
		LogScheduleJobDTO log = new LogScheduleJobDTO();
        log.setJobId(scheduleJob.getJobId());
        log.setJobBeanName(scheduleJob.getJobBeanName());
        log.setJobMethodName(scheduleJob.getJobMethodName());
        log.setJobParams(scheduleJob.getJobParams());
		log.setJobCornExpression(scheduleJob.getJobCronExpression());
		log.setJobParams(scheduleJob.getJobParams());
        log.setLsgStartTime(new Date());
        //默认设置为执行中
		log.setLsgStatus(1);
        //任务开始时间
        long startTime = System.currentTimeMillis();
        try {
            //执行任务
        	logger.info("任务准备执行，任务ID：" + scheduleJob.getJobId());
            ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getJobBeanName(),scheduleJob.getJobMethodName(), scheduleJob.getJobParams());
            Future<?> future = service.submit(task);
			future.get();
			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			log.setLsgTimes((int)times);
			//设置为执行成功
			log.setLsgStatus(2);
			log.setLsgResultMsg("执行完成");
			logger.info("任务执行完毕，任务ID：" + scheduleJob.getJobId() + "  总共耗时：" + times + "毫秒");
		} catch (Exception e) {
			logger.error("任务执行失败，任务ID：" + scheduleJob.getJobId(), e);
			//任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			log.setLsgTimes((int)times);
			//设置为执行失败
			log.setLsgStatus(3);
			log.setLsgResultMsg(StringUtils.substring(e.toString(), 0, 2000));
		}
        log.setLsgEndTime(new Date());
        try {
			scheduleJobLogService.saveLogScheduleJob(log);
		} catch (Exception e) {
        	logger.info("记录定时任务日志异常");
			e.printStackTrace();
		}
    }
}
